# -*- coding: utf-8 -*-
# @Env    : v-3.5.4
# @File   : blog.PY
# @Author : Kevin.Liu
# @Date   : 2019/1/5
# @Desc   : 视图展示
from datetime import datetime
from os import path
from uuid import uuid4

from flask import render_template, Blueprint, url_for
from sqlalchemy import func

from blog.forms import CommentFrom, PostForm
from blog.models import db, Post, Tag, post_tags, Comment, User

blog_blueprint = Blueprint("blog", __name__, template_folder=path.join(path.pardir, "templates", "blog")
                           , url_prefix="/blog")


def sidebar_data():
    """设置侧边栏功能"""
    # 获取最近5篇文章
    recent = db.session.query(Post).order_by(Post.publish_date.desc()).limit(5).all()

    top_tags = db.session.query(Tag, func.count(post_tags.c.post_id).label("total")).join(post_tags).group_by(Tag). \
        order_by("total DESC").limit(5).all()

    return recent, top_tags


@blog_blueprint.route("/")
@blog_blueprint.route("/<int:page>")
def home(page=1):
    """查看主页的功能"""
    posts = Post.query.order_by(Post.publish_date.desc()).paginate(page, 10)

    recent, top_tags = sidebar_data()

    return render_template("home.html", posts=posts, recent=recent, top_tags=top_tags)


@blog_blueprint.route("/post/<string:post_id>", methods=("GET", "POST"))
def post(post_id):
    """查看帖子页面的功能"""

    # 评价表单
    form = CommentFrom()
    # 校验并存储
    if form.validate_on_submit():
        new_comment = Comment(id=str(uuid4()), name=form.name.data)
        new_comment.text = form.text.data
        new_comment.date = datetime.now()
        new_comment.post_id = post_id
        db.session.add(new_comment)
        db.session.commit()

    post = Post.query.get_or_404(post_id)
    tags = post.tags
    comments = post.comments.order_by(Comment.date.desc()).all()
    recent, top_tags = sidebar_data()
    return render_template("post.html", post=post, tags=tags, comments=comments, form=form,
                           recent=recent,
                           top_tags=top_tags)


@blog_blueprint.route("/tag/<string:tag_name>")
def tag(tag_name):
    """查看标签页面的功能"""

    tag = Tag.query.filter_by(name=tag_name).first_or_404()
    posts = tag.posts.order_by(Post.publish_date.desc()).all()
    recent, top_tags = sidebar_data()
    return render_template("tag.html", tag=tag, posts=posts, recent=recent, top_tags=top_tags)


@blog_blueprint.route("/user/<string:username>")
def user(username):
    """查看用户页面的功能"""
    user = db.session.query(User).filter_by(username=username).first_or_404()
    posts = user.posts.order_by(Post.publish_date.desc()).all()
    recent, top_tags = sidebar_data()

    return render_template("user.html", user=user, posts=posts, recent=recent, top_tags=top_tags)


@blog_blueprint.route("/new", methods=["GET", "POST"])
def new_post():
    """新建文章"""
    form = PostForm()

    if form.validate_on_submit():
        new_post = Post(id=str(uuid4()), title=form.title.data)
        new_post.text = form.text.data
        new_post.publish_date = datetime.now()
        db.session.add(new_post)
        db.session.commit()

    return render_template("new.html", form=form)


@blog_blueprint.route("/edit/<string::id>", methods=["GET", "POST"])
def edit_post(id):
    """编辑文章"""
    post = Post.query.get_or_404(id)
    form = PostForm()

    if form.validate_on_submit():
        post.title = form.title.data
        post.text = form.text.data
        post.publish_date = datetime.now()
        db.session.add(post)
        db.session.commit(post)

        return render_template(url_for("blog.post", post_id=post.id))

    form.text.data = post.text
    return render_template("edit.html", form=form, post=post)


@blog_blueprint.errorhandler(404)
def page_not_found(error):
    """未找到用户页面"""
    return render_template("Page_not_found.html"), 404
